import axios from 'axios'
import router from '@/router/router-static'
import storage from '@/utils/storage'
import {MessageBox} from "element-ui";

const http = axios.create({
    timeout: 1000 * 86400,
    withCredentials: true,
    baseURL: '/api',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
// 请求拦截
http.interceptors.request.use(config => {
    config.headers['Token'] = storage.get('Token') // 请求头带上token
    return config
}, error => {
    return Promise.reject(error)
})
// 响应拦截
http.interceptors.response.use(response => {
    if (response.data && response.data.code === 401) { // 401, token失效
        if (router.currentRoute.name !== 'login') { // 防止重复弹窗和跳转
            MessageBox.alert(response.data.message || 'token失效！', '提示', {
                confirmButtonText: '确定',
                type: 'warning',
                callback: () => {
                    router.push({ name: 'login' });
                }
            });
        }
    } else if (response.data && response.data.code === 406) {
        // 使用MessageBox展示信息并在点击确定后跳转到登录页
        if (router.currentRoute.name !== 'login') { // 防止重复弹窗和跳转
            MessageBox.alert(response.data.message || '权限验证失败！', '提示', {
                confirmButtonText: '确定',
                type: 'warning',
                callback: () => {
                    router.push({ name: 'login' });
                }
            });
        }
    }else if (response.data && response.data.code === 400) {
        // 使用MessageBox展示信息并在点击确定后跳转到登录页
        if (router.currentRoute.name !== 'login') { // 防止重复弹窗和跳转
            MessageBox.alert(response.data.message || 'token不存在', '提示', {
                confirmButtonText: '确定',
                type: 'warning',
                callback: () => {
                    router.push({ name: 'login' });
                }
            });
        }
    }
    return response;
}, error => {
    return Promise.reject(error)
})
export default http